import React from 'react';
import PropTypes from 'prop-types';
import { Form, Field, Balloon, Input } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import exceed from 'utils/apimap';
import ImportProjectListModal from 'components/importProjectListModal';
import AccountMessage from '../accountMessage';
import CONSTANTS from 'utils/constants.js';
// import NoRight from '../accountMessage/noRIght';
import { encrypt } from 'utils/JSEncrypt';
import utils from 'utils';
import docs from 'utils/docs';
import LoadingAccount from '../accountMessage/loading';
import track from 'utils/track';
import './index.scss';
import intl from '../../../locale';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

const { PLATFORM_TYPES } = CONSTANTS;
const auto_bind = utils.getUrlSearchParam('auto_bind') || '';

export default class ImportProjectByUrlModal extends React.Component {
  static propTypes = {
    closeModal: PropTypes.func,
    platform_type: PropTypes.string,
  };

  static defaultProps = {
    closeModal: () => {},
    platform_type: 'GITEE',
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      isFullScreenModalShow: false,
      accountInfo: {},
      isGetttingAccount: false,
      isFirst: true, // token方式有帐号则为false, 无帐号为true; oAuth始终是true
      // tb关联的第三方帐号
      // tbAliens: [],
      // 2019-11-26 码云oAuth去除，前端直接去除入口即可
      // isTokenShow: true,
    };
  }

  componentDidMount() {
    this.getAccountInfo();
  }

  getAccountInfo = () => {
    // 查询有无帐号，有帐号：token则显示帐号即可，oAuth则去绑定；无帐号也是绑定
    this.setState({
      isGetttingAccount: true,
    });

    this.props.setDisabled(true);
    exceed
      .fetch({
        api: 'projects.import.account.get',
        data: { platform_type: this.props.platform_type },
      })
      .then((result) => {
        // oAuth则显示跳转
        if (result.bind_type !== 'TOKEN') {
          this.autoBindAccount();
        } else {
          this.setState({
            accountInfo: result,
            isGetttingAccount: false,
            isFirst: false,
          });

          this.props.setDisabled(false);
        }
      })
      .fail((err) => {
        this.autoBindAccount();
        console.error(err);
      });
  };

  autoBindAccount = () => {
    if (auto_bind === 'gitee' && !window.sessionStorage.getItem('gitee')) {
      const { platform_type } = this.props;
      const data = {
        platform_type,
        platform_host: (PLATFORM_TYPES[platform_type] && PLATFORM_TYPES[platform_type].host) || '',
        token: '',
        token_encrypted_type: 'text',
        override: true,
      };

      exceed
        .fetch({
          api: 'projects.import.account.post',
          data,
        })
        .then((accountInfo) => {
          // 刷新后清除
          window.sessionStorage.setItem('gitee', 'loaded');

          this.setState({
            isGetttingAccount: false,
            accountInfo,
            isFullScreenModalShow: auto_bind === 'gitee',
          });

          this.props.setDisabled(false);
        })
        .fail((err) => {
          this.setState({
            isGetttingAccount: false,
          });

          this.props.setDisabled(false);
          console.error(err);
        });
    } else {
      this.setState({
        isGetttingAccount: false,
      });

      this.props.setDisabled(false);
    }
  };

  handleOk = () => {
    const { accountInfo } = this.state;
    const { platform_type } = this.props;
    // 已绑定帐号直接打开弹窗
    if (Object.keys(accountInfo).length) {
      this.setState({
        isFullScreenModalShow: true,
      });

      return;
    }
    this.field.validate((errors) => {
      if (!errors) {
        if (this.props.submitting) {
          return;
        }
        this.props.setSubmitting(true);
        const formData = this.field.getValues();
        if (formData.token) {
          formData.token_encrypted_type = 'rsa'; // 使用加密
          formData.token = encrypt(formData.token, this.props.PUBLIC_KEY);
        } else {
          formData.token_encrypted_type = 'text';
        }
        const data = {
          platform_type,
          platform_host:
            (PLATFORM_TYPES[platform_type] && PLATFORM_TYPES[platform_type].host) || '',
          token: formData.token,
          token_encrypted_type: formData.token_encrypted_type,
          override: true,
        };

        this.formSubmit(data, () => {
          this.props.setSubmitting(false);
        });
      }
    });
  };

  formSubmit = (formData, cb) => {
    exceed
      .fetch({
        api: 'projects.import.account.post',
        data: formData,
      })
      .then((result) => {
        this.setState({
          isFullScreenModalShow: true,
          accountInfo: result,
          isFirst: true,
        });

        cb && cb();
      })
      .fail((err) => {
        cb && cb();
        console.error(err);
      });
  };

  unbindCallback = () => {
    //  token 方式
    this.setState({
      accountInfo: {},
      isFirst: false,
    });
  };

  // 解绑后的操作
  handleUnbind = () => {
    this.getNewData();
  };

  getNewData = () => {
    this.setState(
      {
        isFullScreenModalShow: false,
        accountInfo: {},
        isGetttingAccount: false,
        isFirst: true,
        // tb关联的第三方帐号
        // tbAliens: [],
        // isTokenShow: false,
      },
      () => {
        this.getAccountInfo();
      },
    );
  };

  goBindAccount = () => {
    const targetUrl = `${window.location.origin}/?auto_bind=gitee`;
    window.location.href = `http://account.teambition.com/gitee/login?next_url=${encodeURIComponent(
      targetUrl,
    )}`;
  };

  render() {
    const { init } = this.field;
    const {
      isFullScreenModalShow,
      accountInfo,
      isGetttingAccount,
      isFirst,
      // isTokenShow,
    } = this.state;

    if (isGetttingAccount) {
      return <LoadingAccount />;
    }
    return (
      <React.Fragment>
        {Object.keys(accountInfo).length ? (
          <AccountMessage accountInfo={accountInfo} unbindCallback={this.unbindCallback} />
        ) : (
          <React.Fragment>
            <Form {...formItemLayout} field={this.field} labelAlign="top">
              <FormItem
                required
                label={
                  <span>
                    <span className="before-icon-text">Access Token</span>
                    <Balloon
                      closable={false}
                      align="t"
                      trigger={
                        <ButtonIcon
                          name="question-line"
                          type="secondary"
                          className="access-token-help"
                        />
                      }
                    >
                      {intl.get({
                        id: 'code-assets.importProjectModal.gitee.AccessTokenIsGeneratedFor',
                        defaultMessage: 'Access Token 生成，请参考',
                      })}

                      <a href={docs('accessTokenGenerated')} target="_blank" rel="noreferrer">
                        {intl.get({
                          id: 'code-assets.importProjectModal.gitee.HelpDocumentation',
                          defaultMessage: '帮助文档',
                        })}
                      </a>
                    </Balloon>
                  </span>
                }
              >
                <Input
                  autoFocus
                  placeholder={intl.get({
                    id: 'code-assets.importProjectModal.gitee.SuchAsSfHnp',
                    defaultMessage: '如 67sf7648hnp',
                  })}
                  {...init('token', {
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.importProjectModal.gitee.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },
                    ],

                    initValue: '',
                    props: {
                      onChange: () => {
                        track({
                          action: 'input_access_token',
                          page: 'Dialog-ImportRepo',
                          type: 'import gitee',
                          control: '',
                        });
                      },
                    },
                  })}
                />
              </FormItem>
            </Form>
            {/* </div> */}
          </React.Fragment>
        )}

        {isFullScreenModalShow ? (
          <ImportProjectListModal
            accountInfo={accountInfo}
            isModalOpen={isFullScreenModalShow}
            closeModal={() => {
              this.setState({
                isFullScreenModalShow: false,
                isFirst: false,
              });
            }}
            handleUnbind={this.handleUnbind}
            isFirst={isFirst}
          />
        ) : null}
      </React.Fragment>
    );
  }
}
